package cc.abanlee.module.system.dal.redis.oauth2;

import cc.abanlee.framework.common.util.json.JsonUtils;
import cc.abanlee.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cc.abanlee.module.system.dal.redis.RedisKeyConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: create by
 * @version: v1.0
 * @description:
 * @date:2022/9/7
 */
@Repository
public class OAuth2AccessTokenRedisDAO {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public OAuth2AccessTokenDO get(String accessToken) {
        String redisKey = formatKey(accessToken);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), OAuth2AccessTokenDO.class);
    }

    public void set(OAuth2AccessTokenDO accessTokenDO) {
        String redisKey = formatKey(accessTokenDO.getAccessToken());


        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(accessTokenDO)
                , accessTokenDO.getExpiresTime().getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    private static String formatKey(String accessToken) {
        return String.format(RedisKeyConstants.OAUTH2_ACCESS_TOKEN.getKeyTemplate(), accessToken);
    }
}
